package com.aspire.boc.mms.gwcmp.action;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.xmlrpc.XmlRpcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;
import com.aspire.boc.mms.gwcmp.dao.GwcmpEcMapper;
import com.aspire.boc.mms.gwcmp.model.GwcmpEc;
import com.aspire.boc.mms.gwcmp.model.GwcmpEcExample;
import com.aspire.boc.mms.gwcmp.util.GwcmpAdminUtil;
import com.aspire.boc.mms.wmf.action.OperLogAct;
import com.aspire.boc.mms.wmf.util.Configuration;
import com.aspire.boc.mms.wmf.util.Json;
import com.aspire.boc.mms.wmf.util.Page;

/**
 * 企业管理
 * @author wangpengfei
 *
 */
@Controller
public class EcAct {
	private static Log log = LogFactory.getLog(OperLogAct.class);
	
	@Autowired
	private GwcmpEcMapper gwcmpecMapper;
	
	/**
	 *新增/修改企业
	 * @param id
	 * @param ecName
	 * @param province
	 * @param industryType
	 * @param constractBeginMonth
	 * @param constractEndMonth
	 * @param paymentType
	 * @param address
	 * @param contactor
	 * @param phone
	 * @param email
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="/ec/saveEc.do")
	@ResponseBody 
	public ResponseEntity<String> saveEc(
		   @RequestParam(value="id", required = false) String id,
		   @RequestParam(value="ecName", required = true) String ecName,
		   @RequestParam(value="province", required = true) String province,
		   @RequestParam(value="industryType", required = false) String industryType,
		   @RequestParam(value="constractBeginMonth", required = true) String constractBeginMonth,
		   @RequestParam(value="constractEndMonth", required = true) String constractEndMonth,
		   @RequestParam(value="paymentType", required = true) Short paymentType,
		   @RequestParam(value="address", required = false) String address,
		   @RequestParam(value="contactor", required = false) String contactor,
		   @RequestParam(value="phone", required = false) String phone,
		   @RequestParam(value="email", required = false) String email,
		   HttpServletRequest request, HttpServletResponse response){
		String operator= GwcmpAdminUtil.getLoginUserName(request); 
		log.info(">>>>>>>>>/ec/saveEc.do ,operator"+operator+"[ecId="+id+" ecName="+ecName+" province="+province+" industryType="+industryType
				+" constractBeginMonth"+constractBeginMonth+" constractEndMonth"+constractEndMonth+" paymentType"+paymentType
				+" address"+address+" contactor"+contactor+" phone"+phone+" email"+email+"]");

		RequestContext requestContext = new RequestContext(request);
		GwcmpEc gwcmpEc = new GwcmpEc();
		StringBuffer errorMsg = new StringBuffer();
		Map<String, Object> result = new HashMap<String, Object>();
		

		if(StringUtils.isBlank(ecName)){
			result.put("failure", Boolean.valueOf(true));
            errorMsg.append("ecName invalid "); 
            log.error("operation: newEc "+errorMsg.toString());
           return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecNameNotExist"));
		}else if(ecName.length()>50){
			result.put("failure", Boolean.valueOf(true));
            errorMsg.append("ecName invalid "); 
            log.error("operation: newEc "+errorMsg.toString());
           return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecNameCodeError"));
		}

		if(StringUtils.isBlank(province)){
			result.put("failure", Boolean.valueOf(true));
            errorMsg.append("province invalid "); 
            log.error("operation: newEc "+errorMsg.toString());
            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecProvinceNotExist"));
		}
		
		if(industryType.length()>25){
			result.put("failure", Boolean.valueOf(true));
            errorMsg.append("industryType invalid "); 
            log.error("operation: newEc "+errorMsg.toString());
            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecIndustryTypeError"));
		}
		
		if(StringUtils.isBlank(constractBeginMonth)){
			result.put("failure", Boolean.valueOf(true));
            errorMsg.append("constractBeginMonth invalid "); 
            log.error("operation: newEc "+errorMsg.toString());
            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecConstractBeginMonthNotExist"));
		}else if(StringUtils.isBlank(constractEndMonth)){
				result.put("failure", Boolean.valueOf(true));
	            errorMsg.append("constractEndMonth invalid "); 
	            log.error("operation: newEc "+errorMsg.toString());
	            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecConstractEndMonthNotExist"));
			}else if(constractBeginMonth.compareTo(constractEndMonth)==1){
					result.put("failure", Boolean.valueOf(true));
		            errorMsg.append("constractEndMonth invalid "); 
		            log.error("operation: newEc "+errorMsg.toString());
		            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecConstractTimeError"));
			}
		
		
		
		if(null==paymentType||"".equals(paymentType)){
			result.put("failure", Boolean.valueOf(true));
            errorMsg.append("paymentType invalid "); 
            log.error("operation: newEc "+errorMsg.toString());
            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecPaymentTypeNotExist"));
		}
		
		if(StringUtils.isNotBlank(address)){
			if(address.length()>100){
				result.put("failure", Boolean.valueOf(true));
	            errorMsg.append("address invalid "); 
	            log.error("operation: newEc "+errorMsg.toString());
	            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecAddressError"));
			}
		}
		
		if(StringUtils.isNotBlank(contactor)){
			if(contactor.length()>50){
				result.put("failure", Boolean.valueOf(true));
	            errorMsg.append("contactor invalid "); 
	            log.error("operation: newEc "+errorMsg.toString());
	            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecContactorError"));
			}
		}
		
		if(StringUtils.isNotBlank(phone)){
			if(phone.length()>50){
				result.put("failure", Boolean.valueOf(true));
	            errorMsg.append("phone invalid "); 
	            log.error("operation: newEc "+errorMsg.toString());
	            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecPhoneError"));
			}
		}
		
		if(StringUtils.isNotBlank(email)){
			if(email.length()>50){
				result.put("failure", Boolean.valueOf(true));
	            errorMsg.append("email invalid "); 
	            log.error("operation: newEc "+errorMsg.toString());
	            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecEmailError"));
			}
		}
			
			
			gwcmpEc.setProvince(province);
			gwcmpEc.setIndustryType(industryType);
			gwcmpEc.setConstractBeginMonth(constractBeginMonth);
			gwcmpEc.setConstractEndMonth(constractEndMonth);
			gwcmpEc.setPaymentType(paymentType);
			gwcmpEc.setAddress(address);
			gwcmpEc.setContactor(contactor);
			gwcmpEc.setPhone(phone);
			gwcmpEc.setEmail(email);
			
			if(StringUtils.isBlank(id)){//新增企业
				GwcmpEcExample example = new GwcmpEcExample();
				GwcmpEcExample.Criteria criteria = example.createCriteria();
				int ecCount = 0;
				criteria.andEcNameEqualTo(ecName);
				try {
					ecCount = gwcmpecMapper.countByExample(example);
				} catch (Exception e) {
					log.error(">>>>>>>>>/ec/saveEc.do,errorMsg",e);
				}
				if(ecCount!=0){
					result.put("failure", Boolean.valueOf(true));
		            errorMsg.append("ecName invalid "); 
		            log.error("operation: newEc "+errorMsg.toString());
		            return returnErrorResponse(result,  requestContext.getMessage("ec.error.ecNameNotRepeat"));
				}else{
					gwcmpEc.setEcName(ecName);
				}
				
				int seq_ec = gwcmpecMapper.getEcIdSequence();
				String ecId = ""+seq_ec;
				gwcmpEc.setId(ecId);
				short status = 1;
				gwcmpEc.setStatus(status);
				gwcmpEc.setLatestOperator(operator);
				gwcmpEc.setLatestOperateTime(new Date());
				int i = 0;
				try {
					i = gwcmpecMapper.insert(gwcmpEc);
				} catch (Exception e) {
					log.error(">>>>>>>>>/ec/saveEc.do,errorMsg",e);
				}
				log.info(">>>>>>>>>/ec/saveEc.do ,operator"+operator+"[ecId="+id+" ecName="+ecName+" province="+province+" industryType="+industryType
						+" constractBeginMonth"+constractBeginMonth+" constractEndMonth"+constractEndMonth+" paymentType"+paymentType
						+" address"+address+" contactor"+contactor+" phone"+phone+" email"+email+"]");
				if(i==1){
					//向权限系统中插入数据
					try {
						Object object = new Object();
					    XmlRpcClient client = new XmlRpcClient(
					    		Configuration.getConfiguration("system.permission.url"));//权限平台rpc地址
					    Vector<Object> params = new Vector<Object>();
					    Hashtable hash = new Hashtable();
					    hash.put("data_id", seq_ec); //企业Id
					    hash.put("data_name", ecName);//企业名称
					    hash.put("data_descr", "");
					    hash.put("enroll_date", new Date());
					    hash.put("user_name", operator);
					    params.add(Configuration.getConfiguration("system.permission.system_def"));//系统定义swt_cms
					    params.add("EcAdmin"); //企业为EcAdmin
					    params.add(hash);
					    object = client.execute(
					           "FineGrainedResService.addDataRow", params);
					    log.info("[" + operator
					           + "][saveEc insert permission Ec]["
					           + ecName + "]" + object);
					} catch (Exception e) {
						log.error(e);
					}
					result.put("success", Boolean.valueOf(true));
		            log.info("operation: newEc, result: successful, gwcmpEc: "+gwcmpEc);
		            return returnSuccessResponse(result, requestContext.getMessage("ec.success.add"));
				}else{
					result.put("failure", Boolean.valueOf(true));
					log.error("operation: newEc, result: failure, gwcmpEc: "+gwcmpEc);
					return returnErrorResponse(result, requestContext.getMessage("ec.failure.add"));
				}
				
			}else{//修改企业
				gwcmpEc.setId(id);
				gwcmpEc.setLatestOperator(operator);
				gwcmpEc.setLatestOperateTime(new Date());
				
				//根据企业名字查询企业
				GwcmpEc ec = null;
				try {
					ec = gwcmpecMapper.selectByName(ecName);
				} catch (Exception e) {
					log.error(">>>>>>>>>/ec/saveEc.do,errorMsg",e);
				}
				if(ec!=null){
					if(!ec.getId().equals(id)){
						result.put("failure", Boolean.valueOf(true));
			            log.error("operation: updateEc, result: failure, gwcmpEc: "+gwcmpEc);
			            return returnErrorResponse(result, requestContext.getMessage("ec.error.ecNameNotRepeat"));
					}
				}
				gwcmpEc.setEcName(ecName);
				int i = 0;
				try {	
					i = gwcmpecMapper.updateByPrimaryKeySelective(gwcmpEc);
				} catch (Exception e) {
					log.error(">>>>>>>>>/ec/saveEc.do,errorMsg",e);
				}
				log.info(">>>>>>>>>/ec/saveEc.do ,operator"+operator+"[ecId="+id+" ecName="+ecName+" province="+province+" industryType="+industryType
						+" constractBeginMonth"+constractBeginMonth+" constractEndMonth"+constractEndMonth+" paymentType"+paymentType
						+" address"+address+" contactor"+contactor+" phone"+phone+" email"+email+"]");
				if(i==1){
					// 更新权限系统中的数据
					try {
					    Object object = new Object();
					    XmlRpcClient client = new XmlRpcClient(
					    		Configuration.getConfiguration("system.permission.url"));
					    Vector<Object> params = new Vector<Object>();
					    Hashtable hash = new Hashtable();
					    int ecId = Integer.parseInt(id);
					    hash.put("data_id", ecId);
					    hash.put("data_name", ecName);
					    hash.put("data_descr", "");
					    hash.put("enroll_date", new Date());
					    hash.put("user_name", operator);
					    params.add(Configuration.getConfiguration("system.permission.system_def"));
					    params.add("EcAdmin");//产品为ProductAdmin，企业为EcAdmin
					    params.add(hash);
					    object = client.execute(
					           "FineGrainedResService.updateDataRow", params);
					    log.info("[" + operator
					           + "][saveEc update permission Ec]["
					           + id + "]["
					           + ecName + "]" + object);
					} catch (Exception e) {
					    log.error(e);
					}
					
					result.put("success", Boolean.valueOf(true));
		            log.info("operation: updateEc, result: successful, gwcmpEc: "+gwcmpEc);
		            return returnSuccessResponse(result, requestContext.getMessage("ec.success.update"));
				}else{
					result.put("failure", Boolean.valueOf(true));
		            log.error("operation: updateEc, result: failure, gwcmpEc: "+gwcmpEc);
		            return returnErrorResponse(result, requestContext.getMessage("ec.failure.update"));
				}
			}
			
	}
	
	/**
	 * 获取企业详情
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/ec/getEcDetail.do")
	public  @ResponseBody Map<String,Object> getEcDetail(
			@RequestParam(value="id", required = true) String id,
			HttpServletRequest request, HttpServletResponse response){
		String operator= GwcmpAdminUtil.getLoginUserName(request);
		log.info(">>>>>>>>>>/ec/getEcDetail.do ,operator"+operator+"[ecId="+id+"]");
		Map<String,Object> result = new HashMap<String, Object>();
		GwcmpEc ec = new GwcmpEc();
		if(StringUtils.isBlank(id)){
			log.error(">>>>>>>>>>/ec/getEcDetail.do,errorMsg:[ecId] null");
			result.put("single", new GwcmpEc());
			return result;
		}
		try {
			ec = gwcmpecMapper.selectByPrimaryKey(id);
			result.put("single", ec);
		} catch (Exception e) {
			log.error(">>>>>>>>>>/ec/getEcDetail.do,errorMsg"+e);
		}
		return result;
	}
	
	/**
	 * 查询企业列表
	 * @param start
	 * @param limit
	 * @param id
	 * @param ecName
	 * @param province
	 * @param constractBeginMonthStart
	 * @param constractBeginMonthEnd
	 * @param constractEndMonthStart
	 * @param constractEndMonthEnd
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/ec/getEcList.do")
	@ResponseBody
	public Map<String,Object> getEcList(
			@RequestParam(value="start", required = true)int start,
			@RequestParam(value="limit", required = true)int limit,
			@RequestParam(value="id", required = false)String id,
			@RequestParam(value="ecName", required = false)String ecName,
			@RequestParam(value="province", required = false)String province,
			@RequestParam(value="constractBeginMonthStart", required = false)String constractBeginMonthStart,
			@RequestParam(value="constractBeginMonthEnd", required = false)String constractBeginMonthEnd,
			@RequestParam(value="constractEndMonthStart", required = false)String constractEndMonthStart,
			@RequestParam(value="constractEndMonthEnd", required = false)String constractEndMonthEnd,
			HttpServletRequest request, HttpServletResponse response){
		String operator= GwcmpAdminUtil.getLoginUserName(request);
		StringBuffer logInfo = new StringBuffer();
		logInfo.append(" operator:").append(operator).append(" url: /ec/getEcList.do")
			.append(" params: [start=").append(start).append(",limit=").append(limit).append(",id=").append(id)
			.append(",ecName=").append(ecName).append(",province=").append(province).append(",constractBeginMonthStart=")
			.append(constractBeginMonthStart).append(",constractBeginMonthEnd=").append(constractBeginMonthEnd)
			.append(",constractEndMonthStart=").append(constractEndMonthStart).append(constractEndMonthEnd)
			.append(constractEndMonthEnd);
		log.info(logInfo.toString());
		Map<String,Object> result = new HashMap<String, Object>();
		GwcmpEcExample example = new GwcmpEcExample();
		GwcmpEcExample.Criteria criteria = example.createCriteria();
		if(StringUtils.isNotBlank(id)){
			criteria.andIdEqualTo(id);
		}
		if(StringUtils.isNotBlank(ecName)){
			criteria.andEcNameLike("%"+ecName+"%");
		}
		if(StringUtils.isNotBlank(province)){
			criteria.andProvinceEqualTo(province);
		}
		if(StringUtils.isNotBlank(constractBeginMonthStart)){
			criteria.andConstractBeginMonthGreaterThanOrEqualTo(constractBeginMonthStart);
		}
		if(StringUtils.isNotBlank(constractBeginMonthEnd)){
			criteria.andConstractBeginMonthLessThanOrEqualTo(constractBeginMonthEnd);
		}
		if(StringUtils.isNotBlank(constractEndMonthStart)){
			criteria.andConstractEndMonthGreaterThanOrEqualTo(constractEndMonthStart);
		}
		if(StringUtils.isNotBlank(constractEndMonthEnd)){
			criteria.andConstractEndMonthLessThanOrEqualTo(constractEndMonthEnd);
		}
		try {
			int total = gwcmpecMapper.countByExample(example);
			result.put("total", total);
		} catch (Exception e) {
			log.error(">>>>>>>>>>/ec/getEcDetail.do,errorMsg"+e);
		}
		
		Page page = new Page(start,limit);
		example.setPage(page);
		example.setOrderByClause("LATEST_OPERATE_TIME");
		
		List<GwcmpEc> list = null;
		try {
			list = gwcmpecMapper.selectByExample(example);
		} catch (Exception e) {
			log.error(">>>>>>>>>>/ec/getEcDetail.do,errorMsg"+e);
		}
		result.put("list", list!=null ? list:new ArrayList<GwcmpEc>(0));
		log.info(">>>>>>>>>>/ec/getEcDetail.do,listSize()="+list.size());
		return result;
	}
	
	/**
	 * 企业导出
	 * @param start
	 * @param limit
	 * @param id
	 * @param ecName
	 * @param province
	 * @param constractBeginMonthStart
	 * @param constractBeginMonthEnd
	 * @param constractEndMonthStart
	 * @param constractEndMonthEnd
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/ec/exportEcList.do")
	@ResponseBody
	public void exportEcList(
			@RequestParam(value="id", required = false)String id,
			@RequestParam(value="ecName", required = false)String ecName,
			@RequestParam(value="province", required = false)String province,
			@RequestParam(value="constractBeginMonthStart", required = false)String constractBeginMonthStart,
			@RequestParam(value="constractBeginMonthEnd", required = false)String constractBeginMonthEnd,
			@RequestParam(value="constractEndMonthStart", required = false)String constractEndMonthStart,
			@RequestParam(value="constractEndMonthEnd", required = false)String constractEndMonthEnd,
			HttpServletRequest request, HttpServletResponse response){
		String operator= GwcmpAdminUtil.getLoginUserName(request);
		StringBuffer logInfo = new StringBuffer();
		logInfo.append(" operator:").append(operator).append(" url: /ec/getEcList.do").append(",id=").append(id)
			.append(",ecName=").append(ecName).append(",province=").append(province).append(",constractBeginMonthStart=")
			.append(constractBeginMonthStart).append(",constractBeginMonthEnd=").append(constractBeginMonthEnd)
			.append(",constractEndMonthStart=").append(constractEndMonthStart).append(constractEndMonthEnd)
			.append(constractEndMonthEnd);
		log.info(logInfo.toString());
		GwcmpEcExample example = new GwcmpEcExample();
		GwcmpEcExample.Criteria criteria = example.createCriteria();
		example.setOrderByClause("LATEST_OPERATE_TIME");
		if(StringUtils.isNotBlank(id)){
			criteria.andIdEqualTo(id);
		}
		if(StringUtils.isNotBlank(ecName)){
			criteria.andEcNameLike("%"+ecName+"%");
		}
		if(StringUtils.isNotBlank(province)){
			criteria.andProvinceEqualTo(province);
		}
		if(StringUtils.isNotBlank(constractBeginMonthStart)){
			criteria.andConstractBeginMonthGreaterThanOrEqualTo(constractBeginMonthStart);
		}
		if(StringUtils.isNotBlank(constractBeginMonthEnd)){
			criteria.andConstractBeginMonthLessThanOrEqualTo(constractBeginMonthEnd);
		}
		if(StringUtils.isNotBlank(constractEndMonthStart)){
			criteria.andConstractEndMonthGreaterThan(constractEndMonthStart);
		}
		if(StringUtils.isNotBlank(constractEndMonthEnd)){
			criteria.andConstractEndMonthLessThan(constractEndMonthEnd);
		}
		List<GwcmpEc> list = null;
		try {
			list = gwcmpecMapper.selectByExample(example);
		} catch (Exception e) {
			log.error(logInfo.toString(),e);
		}
		if(list == null) new ArrayList<GwcmpEc>(0);
        HSSFWorkbook wb = writeEcInfoExcelOutputStream(list, response);
		String filename = "QYGL_"
				+ new SimpleDateFormat("yyyyMMdd").format(new Date())
				+ ".xls";
		downloadExcel(wb, filename, response);
	}
	
	//创建工作量excel文件
	private HSSFWorkbook writeEcInfoExcelOutputStream(List<GwcmpEc> list, HttpServletResponse response){
		/**
 		 * List<Map<String, Object>>
 		 */
 		HSSFWorkbook wb = new HSSFWorkbook();
 		HSSFCellStyle numStyle = wb.createCellStyle();
 		numStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
 		int size = list == null ? 0 : list.size();
 		if(size>0){
 			int sheetSize = 5000;
 			int sheetCount = (int)Math.ceil(size/sheetSize+1);
 			for (int n = 0; n < sheetCount; n++) {
 				HSSFSheet sheet = wb.createSheet("表"+(n+1));
 				sheet.setDefaultColumnWidth((short) 10);
				HSSFRow rowHead = sheet.createRow(0);
				rowHead.createCell((short) 0).setCellValue(
						new HSSFRichTextString("企业ID"));
				rowHead.createCell((short) 1).setCellValue(
						new HSSFRichTextString("企业名称"));
				rowHead.createCell((short) 2).setCellValue(
						new HSSFRichTextString("所属省份"));
				rowHead.createCell((short) 3).setCellValue(
						new HSSFRichTextString("行业类别"));
				rowHead.createCell((short) 4).setCellValue(
						new HSSFRichTextString("起始时间"));
				rowHead.createCell((short) 5).setCellValue(
						new HSSFRichTextString("终止时间"));
				rowHead.createCell((short) 6).setCellValue(
						new HSSFRichTextString("付费方式"));
				rowHead.createCell((short) 7).setCellValue(
						new HSSFRichTextString("地址"));
				rowHead.createCell((short) 8).setCellValue(
						new HSSFRichTextString("联系人"));
				rowHead.createCell((short) 8).setCellValue(
						new HSSFRichTextString("电话"));
				rowHead.createCell((short) 10).setCellValue(
						new HSSFRichTextString("邮箱"));
				
				for (int i = n * sheetSize; i < list.size() && i<(n+1)*sheetSize; i++) {
					HSSFRow rowBody = sheet.createRow(i % sheetSize+1);
					GwcmpEc ec = list.get(i);
					rowBody.createCell((short) 0).setCellValue(
							new HSSFRichTextString(getNullString(ec.getId())));
					rowBody.createCell((short) 1).setCellValue(
							new HSSFRichTextString(getNullString(ec.getEcName())));
					rowBody.createCell((short) 2).setCellValue(
							new HSSFRichTextString(getNullString(ec.getProvince())));
					rowBody.createCell((short) 3).setCellValue(
							new HSSFRichTextString(getNullString(ec.getIndustryType())));
					rowBody.createCell((short) 4).setCellValue(
							new HSSFRichTextString(getNullString(ec.getConstractBeginMonth())));
					rowBody.createCell((short) 5).setCellValue(
							new HSSFRichTextString(getNullString(ec.getConstractEndMonth())));
					String paymentType = null;
					if(ec!=null){
						if(1==ec.getPaymentType()){
							paymentType = "后付";
						}else if(2==ec.getPaymentType()){
							paymentType = "预付";
						}
					}
					rowBody.createCell((short) 6).setCellValue(
							new HSSFRichTextString(getNullString(paymentType)));
					rowBody.createCell((short) 7).setCellValue(
							new HSSFRichTextString(getNullString(ec.getAddress())));
					rowBody.createCell((short) 8).setCellValue(
							new HSSFRichTextString(getNullString(ec.getContactor())));
					rowBody.createCell((short) 9).setCellValue(
							new HSSFRichTextString(getNullString(ec.getPhone())));
					rowBody.createCell((short) 10).setCellValue(
							new HSSFRichTextString(getNullString(ec.getEmail())));
				}
			}
 		}
		return wb;
	}
	
	/**
	 * @param wb
	 * @param filename
	 * @param response
	 */
	private void downloadExcel(HSSFWorkbook wb, String filename,
			HttpServletResponse response) {

		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setHeader("Content-Type", "application/force-download");
			response.setHeader("Content-Disposition", "attachment;filename="
					+ URLEncoder.encode(filename, "UTF-8"));
			wb.write(out);
			out.close();
		} catch (Exception e) {
			log.error(">>>>>fail to write output stream", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					log.error(">>>>>fail to close output stream", e);
				}
			}
		}
	}
	
	private String getNullString(Object data){
		if(data == null){
			return "";
		}
		String dataStr = String.valueOf(data);
		if("null".equalsIgnoreCase(dataStr)){
			return "";
		}
		return dataStr;
	}
	
	/**
     * 返回错误响应消息
     * @param result
     * @param errMsg
     * @return
     */
    private ResponseEntity<String> returnErrorResponse(Map<String, Object> result, String errMsg) {
        result.put("failure", Boolean.valueOf(true));
        result.put("msg", errMsg);
        return new ResponseEntity<String>(Json.toJson(result), getHttpHeaders(), HttpStatus.OK);
    }
    
    /**
	 * 返回成功响应消息
	 * @param result
	 * @param errMsg
	 * @return
	 */
	private ResponseEntity<String> returnSuccessResponse(Map<String, Object> result, String errMsg) {
		result.put("success", Boolean.valueOf(true));
		result.put("msg", errMsg);
		return new ResponseEntity<String>(Json.toJson(result),
				getHttpHeaders(), HttpStatus.OK);
	}
    
    /**
     * 获取http消息头
     * @return
     */
    private HttpHeaders getHttpHeaders() {        
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType mediaType = new MediaType("text", "html", Charset.forName("utf-8"));
        httpHeaders.setContentType(mediaType);
        return httpHeaders;
    }
}
